package cn.iwgang.countdownview;


import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.Optional;

/**
 * Utils
 * Created by iWgang on 16/6/19.
 * https://github.com/iwgang/CountdownView
 */
public  class Utils {

    public static int dp2px(Context context, float dpValue) {
        if (dpValue <= 0) return 0;
//        final float scale = context.getResources().getDisplayMetrics().density;
        Optional<Display> defaultDisplay = DisplayManager.getInstance().getDefaultDisplay(context);
        if(defaultDisplay.isPresent()){
            DisplayAttributes attributes = defaultDisplay.get().getAttributes();
            return (int) (dpValue * attributes.scalDensity + 0.5f);
        }
        return 0;

    }

    public static int sp2px(Context context, float spValue) {
        if (spValue <= 0){
            return 0;
        }
        Optional<Display> defaultDisplay = DisplayManager.getInstance().getDefaultDisplay(context);
        if(defaultDisplay.isPresent()){
            DisplayAttributes attributes = defaultDisplay.get().getAttributes();
            return (int) (spValue * attributes.scalDensity + 0.5f) ;
        }
        return 0;
    }

    public static String formatNum(int time) {
        return time < 10 ? "0" + time : String.valueOf(time);
    }

    public static String formatMillisecond(int millisecond) {
        String retMillisecondStr;

        if (millisecond > 99) {
            retMillisecondStr = String.valueOf(millisecond / 10);
        } else if (millisecond <= 9) {
            retMillisecondStr = "0" + millisecond;
        } else {
            retMillisecondStr = String.valueOf(millisecond);
        }

        return retMillisecondStr;
    }

}
